/*
 * Copyright (c) 2020 WildFireChat. All rights reserved.
 */

package cn.wildfire.chat.app.login;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.text.Editable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnEditorAction;
import butterknife.OnTextChanged;
import cn.wildfire.chat.app.AppService;
import cn.wildfire.chat.app.login.model.LoginResult;
import cn.wildfire.chat.app.login.model.RegisterResult;
import cn.wildfire.chat.app.main.MainActivity;
import cn.wildfire.chat.kit.ChatManagerHolder;
import cn.wildfire.chat.kit.WfcBaseActivity;
import cn.wildfirechat.chat.R;

/**
 * use {@link SMSLoginActivity} instead
 */
//@Deprecated
public class LoginActivity extends WfcBaseActivity {
    @BindView(R.id.loginButton)
    Button loginButton;
    @BindView(R.id.accountEditText)
    EditText accountEditText;
    @BindView(R.id.passwordEditText)
    EditText passwordEditText;
    @BindView(R.id.tv_create_user)
    TextView tvCreate;
    private boolean isCreate = false;
    private InputMethodManager imm;
    @Override
    protected int contentLayout() {
        return R.layout.login_activity_account;
    }

    @Override
    protected void afterViews() {
        passwordEditText.setCursorVisible(true);//动态代码设置显示光标方式
        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        passwordEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {//点击软键盘完成控件时触发的行为
                //关闭光标并且关闭软键盘
                    passwordEditText.setCursorVisible(false);
                    imm.hideSoftInputFromWindow(getCurrentFocus().getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                }
                return true;//消费掉该行为
            }
        });
    }

    @Override
    protected boolean showHomeMenuItem() {
        return false;
    }

    @OnTextChanged(value = R.id.accountEditText, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    void inputAccount(Editable editable) {
        if (!TextUtils.isEmpty(passwordEditText.getText()) && !TextUtils.isEmpty(editable)) {
            loginButton.setEnabled(true);
        } else {
            loginButton.setEnabled(false);
        }
    }

    @OnTextChanged(value = R.id.passwordEditText, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    void inputPassword(Editable editable) {
//        passwordEditText.setCursorVisible(false);//动态代码设置隐藏guangbiao
//        InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//        im.hideSoftInputFromWindow(getCurrentFocus().getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        if (!TextUtils.isEmpty(accountEditText.getText()) && !TextUtils.isEmpty(editable)) {
            loginButton.setEnabled(true);
        } else {
            loginButton.setEnabled(false);
        }
    }
    @OnClick(R.id.loginButton)
    void login() {
        String account = accountEditText.getText().toString().trim();
        String password = passwordEditText.getText().toString().trim();
        if(isCreate){//创建用户
            MaterialDialog dialog = new MaterialDialog.Builder(this)
                    .content("注册中...")
                    .progress(true, 10)
                    .cancelable(false)
                    .build();
            dialog.show();
            AppService.Instance().createUser(account, password, new AppService.RegisterCallback() {
                @Override
                public void onUiSuccess(String result) {
                    dialog.dismiss();
                    if (isFinishing()) {
                        return;
                    }
                    try {
                        JSONObject success = new JSONObject(result);
                        Toast.makeText(LoginActivity.this,success.getString("result") , Toast.LENGTH_SHORT).show();
                        loginButton.setText("登录");
                        loginButton.setEnabled(true);
                        isCreate = false;
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                }

                @Override
                public void onUiFailure(int code, String msg) {
                    if (isFinishing()) {
                        return;
                    }
                    dialog.dismiss();
                    Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_SHORT).show();
                }
            });
            return;
        }
        MaterialDialog dialog = new MaterialDialog.Builder(this)
                .content("登录中...")
                .progress(true, 10)
                .cancelable(false)
                .build();
        dialog.show();
        AppService.Instance().pwLogin(account, password, new AppService.LoginCallback() {
            @Override
            public void onUiSuccess(LoginResult loginResult) {
                if (isFinishing()) {
                    return;
                }
                dialog.dismiss();
                //需要注意token跟clientId是强依赖的，一定要调用getClientId获取到clientId，然后用这个clientId获取token，这样connect才能成功，如果随便使用一个clientId获取到的token将无法链接成功。
                ChatManagerHolder.gChatManager.connect(loginResult.getUserId(), loginResult.getToken());
                SharedPreferences sp = getSharedPreferences("config", Context.MODE_PRIVATE);
                sp.edit()
                    .putString("id", loginResult.getUserId())
                    .putString("token", loginResult.getToken())
                    .apply();
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
                finish();
            }

            @Override
            public void onUiFailure(int code, String msg) {
                if (isFinishing()) {
                    return;
                }
                dialog.dismiss();
                Toast.makeText(LoginActivity.this,  msg, Toast.LENGTH_SHORT).show();
            }
        });

    }
    @OnClick(R.id.tv_create_user)
    void toCreate() {
        if(isCreate) {
            tvCreate.setText("没有账户,创建账户");
            loginButton.setText("登录");
            isCreate = false;
        }else{
            loginButton.setText("注册");
            tvCreate.setText("返回登录");
            isCreate = true;

        }
    }
}
